<template>
  <el-dialog
      v-model="showDialog"
      title="Tips"
      width="30%"
  >
    <span style="margin-right: 20px;">{{ link }}</span>
    <el-icon @click="copyLink" style="font-size: 20px;cursor: pointer" color="#409eff">
      <CopyDocument/>
    </el-icon>
    <span @click="copyLink" style="font-size: 20px;color: #409eff;cursor: pointer">复制链接</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="showDialog = false">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, computed} from 'vue'
import {ElMessageBox} from 'element-plus'
import {_msgBox} from '@/utils/msg';


const emit = defineEmits(['update:linkDialog'])

const props = defineProps(
    {
      linkDialog: {
        type: Boolean,
        default: false
      },
      link: {
        type: String,
        required: true,
      }
    }
)
const showDialog = computed({
  get() {
    return props.linkDialog;
  },
  set(v) {
    emit('update:linkDialog', v);
  },
});

function copyToClipboard(textToCopy: string) {
  // navigator clipboard 需要https等安全上下文
  if (navigator.clipboard && window.isSecureContext) {
    // navigator clipboard 向剪贴板写文本
    return navigator.clipboard.writeText(textToCopy);
  } else {
    // 创建text area
    let textArea = document.createElement("textarea");
    textArea.value = textToCopy;
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute";
    textArea.style.opacity = '0';
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand('copy') ? res(null) : rej();
      textArea.remove();
    });
  }
}


const copyLink = () => {
  copyToClipboard(props.link).then(res => {
    _msgBox('已复制连接！', 'success')

  })
}
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
